package com.itesm.distribuidos.mexicantrain;

import java.awt.GridLayout;
import java.util.Stack;
import javax.swing.JPanel;

public class GameBoard extends JPanel {
	private static final long serialVersionUID = 5670834184508236790L;
	private TrainTrack[] tracks = new TrainTrack[9];
	private boolean openDouble = false;
	private boolean lockedLine = false;
	private int playerWithOpenDouble = 100;

	public GameBoard(int round) {
		this.setLayout(new GridLayout(9,1));
		tracks[0] = new TrainTrack("Mexican Train Line : ",round);
		tracks[0].setAvailability(true);
		this.add(tracks[0]);
		for (int i=1; i<tracks.length; i++) {
			tracks[i] = new TrainTrack("Player " + i + " Train Line : ",round);
			this.add(tracks[i]);
		}
	}

	public void setTile(Domino tile) {
		int player = tile.getUser();
		if (player != 0) {
			if (tracks[player].getAvailability()) { 
				if (tracks[player].isMarked()) {
					tracks[player].remove(tracks[player].getComponentCount()-1);
					tracks[player].setMarked(false);
				}
			}
		}
		if (tracks[player].getComponentCount() > 8) { tracks[player].remove(1); }
		tracks[player].add(new DominoButton("Images/"+tile.getSideA()+"-"+tile.getSideB()+".jpg").getButton());
		tracks[player].setTail(tile.getSideB());
		if (tracks[player].getAvailability() && player != 0) { setMarker(player); }
		if (tile.isDouble()) {
			openDouble = true;
			playerWithOpenDouble = tile.getUser();
		}
		else if (playerWithOpenDouble == tile.getUser()) {
			openDouble = false;
			lockedLine = false;
		}
	}

	public void setMarker(int player) {
		if (tracks[player].getComponentCount() > 8) { tracks[player].remove(1); }
		tracks[player].add(new DominoButton("Images/marker.jpg").getButton());
		tracks[player].setMarked(true);
	}

	public GameBoard getBoard() {
		return this;
	}

	public int lastTile(int player) {
		return tracks[player].getTail();
	}

	public TrainTrack[] getTracks() {
		return this.tracks;
	}

	public Stack<Integer> getPlayersAvailable() {
		Stack<Integer> players = new Stack<Integer>();
		for (int i=tracks.length-1; i>=0; i--) {
			if (tracks[i].getAvailability()) {
				players.push(i);
			}
		}
		return players;
	}

	public void changePlayerAvailability(int player) {
		if (!tracks[player].getAvailability()) {
			tracks[player].setAvailability(true);
			setMarker(player);
		}
	}

	public void lockLine() {
		this.lockedLine = true;
	}

	public boolean getLock() {
		return this.lockedLine;
	}

	public boolean isPlayerOpen(int player) {
		return tracks[player].getAvailability();
	}

	public boolean openDouble() {
		return this.openDouble;
	}

	public int playerWithDouble() {
		return playerWithOpenDouble;
	}

	public void closeLine(int player) {
		tracks[player].setAvailability(false);
		if (tracks[player].isMarked()) {
			tracks[player].remove(tracks[player].getComponentCount()-1);
			tracks[player].setMarked(false);
		}
	}
}
